﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace QueueMgrUtil
{
    public class BlockReadQueue<T> 
    {
        
        private Queue<T> _itemsQueue = null;
        EventWaitHandle _wh;

        public BlockReadQueue()
        {
            _wh = new AutoResetEvent(false);
            _itemsQueue = new Queue<T>();
        }

        public void Enqueue(T item)
        {
            lock (_itemsQueue)
            {
                _itemsQueue.Enqueue(item);
            }
            _wh.Set();
        }

        public T Dequeue()
        {
            T dequeuedItem = default(T);

            while (true)
            {
                lock (_itemsQueue)
                {
                    if (_itemsQueue.Count > 0)
                    {
                        dequeuedItem = _itemsQueue.Dequeue();
                        return dequeuedItem;
                    }

                }                
               _wh.WaitOne();
            }
        }

        public long Count 
        {
            get { lock (_itemsQueue) return _itemsQueue.Count; }
        }  

    }
}

